<template>
  <div class="excel-upload-page">
    <header>
      <el-upload
        class="upload-header-area"
        :action="uploadUrl"
        :multiple="false"
        :file-list="fileList"
        :before-upload="uploadExcelFile"
      >
        <el-button type="primary" size="small">
          {{ $t("EXCEL.UploadExcelFile") }}
        </el-button>
        <el-tag
          class="show-file-tag"
          v-show="uploadName"
          :closable="true"
          @close="handleCloseTag"
        >
          {{ `${$t("EXCEL.UploadFileName")}: uploadName` }}
        </el-tag>
      </el-upload>
    </header>
    <section>
      <PaginationTable
        :columns="tableColumns"
        :data="tableData"
        :table-height="600"
        :striped="true"
        :is-show-number="true"
      />
    </section>
  </div>
</template>

<script>
import excel from "@/libs/export-excel";
import { setExcelString } from "@/libs/utils";

export default {
  name: "ExcelUploadPage",
  data() {
    return {
      uploadUrl: "//localhost:80",
      fileList: [],
      uploadName: "",
      tableColumns: [],
      tableData: [],
    };
  },
  methods: {
    /**
     * upload-excel-file
     * @param {File} file upload-file
     */
    uploadExcelFile(file) {
      this.handleCloseTag();

      const reader = new FileReader();
      reader.readAsArrayBuffer(file);

      this.uploadName = file.name;

      reader.onload = (e) => {
        const data = e.target.result;
        const { header, results } = excel.read(data, "utf-8");

        this.setTableColumns(header);
        this.setTableData(results);
      };
    },
    setTableColumns(headers) {
      this.tableColumns = [];

      headers.forEach((h) => {
        this.tableColumns.push({
          prop: setExcelString(h),
          label: setExcelString(h),
        });
      });
    },
    setTableData(results = []) {
      // console.log(results);

      results.forEach((item) => {
        const tableItem = {};

        Object.keys(item).forEach((k) => {
          const itemKey = setExcelString(k),
            itemValue = setExcelString(item[k]);

          tableItem[itemKey] = itemValue;
        });

        this.tableData.push(tableItem);
      });
    },
    handleCloseTag() {
      this.uploadName = "";
      this.tableColumns = [];
      this.tableData = [];
    },
  },
};
</script>

<style scoped lang="scss">
.excel-upload-page {
  width: 100%;
  .upload-header-area {
    padding: 10px 0;
    .show-file-tag {
      margin-left: 5px;
    }
  }
}
</style>
